package com.isxcode.link.common.config;

import com.isxcode.link.common.constant.MsgConstants;
import com.isxcode.link.common.constant.SecurityConstants;
import com.isxcode.link.common.constant.UrlConstants;
import com.isxcode.link.common.pojo.LinkResponse;
import com.isxcode.link.common.properties.LinkClientProperties;
import com.isxcode.link.common.properties.LinkPluginProperties;
import com.isxcode.link.common.template.LinkTemplate;
import com.isxcode.link.common.utils.HttpUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.ResourceAccessException;

import java.util.HashMap;
import java.util.Map;

@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties({LinkPluginProperties.class, LinkClientProperties.class})
public class LinkAutoConfig {

    private final LinkClientProperties linkClientProperties;

    /**
     * 初始化用户默认配置的节点信息
     *
     * @param linkNodeProperties 结点配置信息
     * @return starTemplate
     */
    @Bean("linkTemplate")
    public LinkTemplate starTemplate(LinkClientProperties linkNodeProperties) {

        return new LinkTemplate(linkNodeProperties);
    }

    /*
     * 测试插件连接是否正常
     *
     * @ispong
     */
    @Bean
    public void checkNodeStatus() {

        if (linkClientProperties.getWorkers() == null) {
            return;
        }

        System.out.println("==============================================");
        linkClientProperties.getWorkers().forEach((k, v) -> {
            // 检查用户配置的节点是否有效
            String heartCheckUrl = String.format(UrlConstants.BASE_URL + UrlConstants.HEART_CHECK_URL, v.getHost(), v.getPort());
            Map<String, String> headers = new HashMap<>();
            headers.put(SecurityConstants.HEADER_AUTHORIZATION, v.getKey());
            try {
                LinkResponse linkResponse = HttpUtils.doGet(heartCheckUrl, headers, LinkResponse.class);
                if (MsgConstants.SUCCESS_CODE.equals(linkResponse.getCode())) {
                    System.out.println("检查节点 " + k + " [ok]");
                } else {
                    System.out.println("检查节点 " + k + " [error]");
                }
            } catch (ResourceAccessException e) {
                System.out.println("检查节点 " + k + " [error]");
            }
        });
        System.out.println("==============================================");
    }
}
